package com.taiyuan.zfmvp.JUC.readAndWrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @param
 * @Author: zhoufang@si-tech.com.cn
 * @Descriiption:
 * @Date 2022/10/6
 * @return
 */


class mycache{
    //创建map
    private volatile Map<String,Object> map = new HashMap<>();

    //创建读写锁
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //放数据
    public void put(String key,Object value){
        //添加写锁
        readWriteLock.writeLock().lock();
        try {
        System.out.println(Thread.currentThread().getName()+" 正在写操作"+ key);

            TimeUnit.SECONDS.sleep(3);
            //放数据
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+" 写完了"+ key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }


    }


    //取数据
    public Object get(String key){
        //添加读锁
        readWriteLock.readLock().lock();
        Object result = null;

        try {
            System.out.println(Thread.currentThread().getName()+" 正在读操作"+ key);
            TimeUnit.SECONDS.sleep(3);
            //放数据
            result = map.get(key);
            System.out.println(Thread.currentThread().getName()+" 读完了"+ result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }


        return  result;
    }

}


public class readWriteLock {

    public static void main(String[] args) {
        mycache m = new mycache();
        //创建线程往里放数据
        for (int i = 0; i < 5; i++) {
            final  int num = 1;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    m.put(num+"",num);
                }
            },String.valueOf(i)).start();
        }


        //创建线程取数据
        for (int i = 0; i < 5; i++) {
            final  int num = 1;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    m.get(num+"");
                }
            },String.valueOf(i)).start();
        }
    }

}
